/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package com.inspur.edp.lcm.metadata.core.manager;

import com.inspur.edp.lcm.metadata.api.entity.MetadataPackageHeader;
import com.inspur.edp.lcm.metadata.api.entity.MetadataProject;
import com.inspur.edp.lcm.metadata.common.FileServiceImp;
import com.inspur.edp.lcm.metadata.common.Utils;
import com.inspur.edp.lcm.metadata.core.MetadataProjectCoreService;
import java.io.File;
import java.util.List;
import org.springframework.util.StringUtils;

public class PackageNameManager {
    private MetadataProjectCoreService metadataProjectCoreService = new MetadataProjectCoreService();

    public String getMdpkgNameByGA(String groupId, String artifactId, String mavenPath, String absolutePath) {
        MetadataProject metadataProjInfo = metadataProjectCoreService.getMetadataProjInfo(absolutePath);
        return getMdpkgNameByGA(groupId, artifactId, mavenPath, metadataProjInfo);
    }

    public String getMdpkgNameByGA(String groupId, String artifactId, String mavenPath, MetadataProject metadataProject) {
        String mdpkgName;

        mdpkgName = getMdpkgNameByGAFromMaven(groupId, artifactId, mavenPath);
        if (!StringUtils.isEmpty(mdpkgName)) {
            return mdpkgName;
        }

        mdpkgName = getMdpkgNameByGASplice(groupId, artifactId, metadataProject);
        if (!StringUtils.isEmpty(mdpkgName)) {
            return mdpkgName;
        }

        mdpkgName = getMdpkgNameFromIndexServer(groupId, artifactId);
        return mdpkgName;
    }

    private String getMdpkgNameByGASplice(String groupId, String artifactId, MetadataProject metadataProjInfo) {
        String mdpkgName = "";
        if ("gsp-common-commoncomponent-api".equals(artifactId)) {
            return "Inspur.Gsp.Common.CommonCmp".toLowerCase();
        }
        if ("gsp-pfcommon-commonudt-api".equals(artifactId)) {
            return "Inspur.Gsp.Common.CommonUdt".toLowerCase();
        }

        String front = groupId.substring(groupId.indexOf(".") + 1);
        String back = artifactId.substring(0, artifactId.indexOf("-api")).replace('-', '.');
        // 新规则生成的前端工程artifect后必然会有-front-api, 与原规则中前端工程后有front应予以区别
        if (back.endsWith("front") && !back.endsWith(".front")) {
            back = back.substring(0, back.length() - 5) + ".front";
        }
        String mdpkgNameLikely = front + '.' + back;
        List<MetadataPackageHeader> metadataPackageRefs = metadataProjInfo.getMetadataPackageRefs();
        if (metadataPackageRefs != null && metadataPackageRefs.size() > 0) {
            MetadataPackageHeader metadataPackageHeader = metadataPackageRefs.stream().filter(ref -> ref.getName().toLowerCase().equals(mdpkgNameLikely)).findFirst().orElse(null);
            if (metadataPackageHeader != null) {
                mdpkgName = metadataPackageHeader.getName();
            }
        }
        return mdpkgName;
    }

    private String getMdpkgNameFromIndexServer(String groupId, String artifactId) {
        IndexServerManager indexServerManager = new IndexServerManager();
        return indexServerManager.getPackageNameByGA(groupId, artifactId);
    }

    private String getMdpkgNameByGAFromMaven(String groupId, String artifactId, String mavenPath) {
        String mdpkgName = "";
        FileServiceImp fileServiceImp = new FileServiceImp();

        // 首先从maven目录获取，以packName开头的目录将被选出来，其余被过滤掉
        File[] dirs = new File(mavenPath).listFiles((dir, name) -> name.startsWith(groupId + "-" + artifactId));
        if (dirs != null && dirs.length > 0) {
            File[] files = dirs[0].listFiles((dir, name) -> name.endsWith(Utils.getMetadataPackageExtension()));
            if (files != null && files.length > 0) {
                mdpkgName = fileServiceImp.getFileNameWithoutExtension(files[0].getPath());
            }
        }
        return mdpkgName;
    }

}
